<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="medium" :inline="true">
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入用户姓名" clearable />
      </el-form-item>
      <el-form-item prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :normalizer="normalizer"
          placeholder="请选择归属部门"
          class="treeselect_main"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="16" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['exam:recode:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="6">
        <div class="inner-select">
          <span>试卷列表：</span>
          <el-select
            v-model="queryParams.paperId"
            placeholder="请选择(可搜索)"
            size="small"
            @change="changePaper"
            :clearable="true"
            filterable
            remote
            :remote-method="searchPlan"
            :loading="searchLoading"
            @blur="onBlur"
          >
            <el-option
              v-for="paper in paperList"
              :key="paper.paperId"
              :value="paper.paperId+''"
              :label="paper.paperName"
            >
              <span style="float: left">{{ paper.paperName }}</span>
              <dict-tag
                style="float: right;"
                :options="dict.type.paper_status"
                :value="paper.paperStatus"
              />
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="inner-select">
          <span>考试状态：</span>
          <el-select
            v-model="queryParams.userPaperStatus"
            placeholder="请选择"
            size="small"
            @change="changePaperStatus"
            :clearable="true"
          >
            <el-option
              v-for="dict in dict.type.user_paper_status"
              :value="dict.value"
              :label="dict.label"
            ></el-option>
          </el-select>
        </div>
      </el-col>
      <div style="display:inline-block">
        <el-button type="primary" size="small" plain @click="handleUserRank">成绩排行榜</el-button>
        <el-button type="primary" size="small" plain @click="handleUserAnalysis">成绩统计分析</el-button>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recodeList">
      <el-table-column label="用户名" align="center" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="姓名" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
      <el-table-column
        label="手机号码"
        align="center"
        prop="phonenumber"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="分数" align="center" prop="userPaperScore" />
      <el-table-column label="考试状态" align="center" prop="userPaperStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_paper_status" :value="scope.row.userPaperStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="答题时间"
        align="center"
        prop="userStartTime"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.userStartTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交卷时间" align="center" prop="userEndTime" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.userEndTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleQuHistory(scope.row)"
            v-hasPermi="['exam:recode:query']"
          >答题记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="queryParams.total>0"
      :total="queryParams.total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户试卷答题详情列表 -->
    <el-drawer
      title="用户答题记录列表"
      :visible.sync="userAns.list"
      direction="rtl"
      size="40%"
      append-to-body
    >
      <el-table v-loading="loading" :data="userAnsList" height="95%">
        <el-table-column label="序号" align="center" width="50">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="题目" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{isObj(scope.row)?scope.row.objContent:scope.row.subContent}}</span>
          </template>
        </el-table-column>
        <el-table-column label="题目类型" align="center">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.qb_qu_type"
              :value="isObj(scope.row)?scope.row.objType:scope.row.subType"
            />
          </template>
        </el-table-column>
        <el-table-column label="题目分数" prop="quScore" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.quScore}}分</span>
          </template>
        </el-table-column>
        <el-table-column label="用户分数" prop="userScore" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.userScore}}分</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleAnsInfo(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 用户试卷答题详情 -->
    <user-ans-qu-info
      :visible.sync="userAns.info"
      :quData="userAnsInfo"
      @updateUserScore="updateUserScore"
    />

    <!-- 成绩排名 -->
    <el-dialog
      title="考试用户成绩排名"
      :visible.sync="userRank.show"
      width="40%"
      append-to-body
      :destroy-on-close="true"
    >
      <div style="height: 60vh;">
        <el-table v-loading="loading" :data="userRank.data" height="100%">
          <el-table-column label="姓名" align="center" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="成绩" align="center" prop="score" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.score!=null">{{scope.row.score}}</span>
              <span v-else>未考试</span>
            </template>
          </el-table-column>
          <el-table-column label="排名" align="center" prop="rank" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.score!=null">{{scope.row.rank}}</span>
              <span v-else>未考试</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 成绩统计图 -->
    <paper-record :visible.sync="paperChart.show" :dataInfo="paperChart.data" />
  </div>
</template>

<script>
import {
  listPaper,
  listRecord,
  listUserAns,
  changeUserScore,
  listUserRank,
  listPaperCensus
} from "@/api/exam/recode";
import { listSimpleDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UserAnsQuInfo from "@/components/QuInfo/userAnsQuInfo.vue";
import PaperRecord from "@/components/Echarts/paperRecord.vue";
export default {
  name: "Question",
  dicts: ["paper_status", "user_paper_status", "qb_qu_type"],
  components: {
    Treeselect,
    UserAnsQuInfo,
    PaperRecord
  },
  data() {
    return {
      // 统计图
      paperChart: {
        show: false,
        data: {}
      },
      // 考试成绩排名
      userRank: {
        show: false,
        data: []
      },
      // 用户答题记录列表
      userAnsList: [],
      // 用户答题详情列表弹框
      userAns: {
        list: false,
        info: false
      },
      // 用户答案详情
      userAnsInfo: {},
      // 试卷列表
      paperList: [],
      // 试卷列表搜索条件
      paperQuery: {
        num: 10,
        paperName: undefined
      },
      // 部门简易信息
      deptOptions: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 下拉框loading
      searchLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 试卷试题表格数据
      recodeList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        userPaperStatus: undefined,
        paperId: undefined,
        name: undefined,
        deptId: undefined
      }
    };
  },
  created() {
    this.getListSimpleDept();
    this.getPaperList();
  },
  methods: {
    /** 获取简易部门列表 */
    getListSimpleDept() {
      listSimpleDept()
        .then(res => {
          this.deptOptions = this.handleTree(res.data, "deptId");
        })
        .finally(() => {});
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 查询试卷试题列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then(res => {
        this.recodeList = res.rows;
        this.queryParams.total = res.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        examId: undefined,
        quId: undefined,
        quType: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.userPaperStatus = undefined;
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "exam/recode/export",
        {
          ...this.queryParams
        },
        `recode_${new Date().getTime()}.xlsx`
      );
    },
    /** 简易试卷列表 */
    getPaperList() {
      listPaper(this.paperQuery).then(res => {
        this.paperList = res.data;
        this.queryParams.paperId =
          this.paperList.length > 0 ? this.paperList[0].paperId : undefined;
        this.getList();
      });
    },
    /** 更改学习计划 */
    changePaper() {
      this.getList();
    },
    /** 更改考试状态 */
    changePaperStatus() {
      this.getList();
    },
    /** 搜索学习计划 */
    searchPlan(paperName) {
      this.searchLoading = true;
      this.paperQuery.paperName = paperName == "" ? undefined : paperName;
      setTimeout(() => {
        listPaper(this.paperQuery)
          .then(res => {
            this.paperList = res.data;
          })
          .finally(() => {
            this.searchLoading = false;
          });
      }, 200);
    },
    /** 学习计划搜索下拉框失去焦点 */
    onBlur() {
      if (this.paperList.length <= 0) {
        this.searchLoading = true;
        setTimeout(() => {
          listPaper(this.paperQuery)
            .then(res => {
              this.paperList = res.data;
            })
            .finally(() => {
              this.searchLoading = false;
            });
        }, 200);
      }
    },
    /** 答题历史记录 */
    handleQuHistory(row) {
      this.userAns.list = true;
      let query = {
        userId: row.userId,
        paperId: this.queryParams.paperId
      };
      this.loading = true;
      listUserAns(query)
        .then(res => {
          this.userAnsList = res.data;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 题目详情 */
    handleAnsInfo(row) {
      this.userAnsInfo = row;
      this.userAns.info = true;
    },
    /** 判断是主观题还是客观题 */
    isObj(data) {
      if (data.objType != undefined || data.objType != null) {
        return true;
      } else {
        return false;
      }
    },
    /** 更改用户分数 */
    updateUserScore(row) {
      let data = {
        id: row.id,
        userId: row.userId,
        paperId: this.queryParams.paperId,
        userScore: row.userScore
      };
      this.loading = true;
      changeUserScore(data)
        .then(res => {
          this.$modal.msgSuccess("更改成功");
          this.loading = false;
          this.userAns.info = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 用户成绩排名 */
    handleUserRank() {
      let query = {
        paperId: this.queryParams.paperId
      };
      this.loading = true;
      listUserRank(query)
        .then(res => {
          this.userRank.show = true;
          this.userRank.data = res.data;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 用户成绩统计分析 */
    handleUserAnalysis() {
      let query = {
        paperId: this.queryParams.paperId
      };
      listPaperCensus(query)
        .then(res => {
          this.paperChart.data = res.data;
          this.paperChart.show = true;
        })
        .finally(() => {});
    }
  }
};
</script>
<style scoped>
.inner-select {
  display: flex;
  justify-content: center;
}
.inner-select span {
  font-size: 16px;
  color: #909399;
  line-height: 32px;
}
.treeselect_main {
  width: 200px;
  height: 36px;
}
</style>